package com.ruoyi.common.utils;


import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String dateMonth(final Date date) {
        return parseDateToStr(YYYY_MM, date);
    }

    public static final String dateYear(final Date date) {
        return parseDateToStr(YYYY, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 获取当天开始时间
     * @return
     */
    public static String getCurrentDateStart(String date){
       return date+" 00:00:00";
    }

    /**
     * 获取当天结束时间
     * @return
     */
    public static String getCurrentDateEnd(String date){
        return date+" 23:59:59";
    }

    /**
     * 获取当前日期天之后的日期
     * @param days
     * @return
     */
    public static String getCurrentDayAfter(int days) {
        LocalDate now = toLocalDate(getNowDate());
        // 将当前日期加上n天
        LocalDate futureDate = now.plusDays(days);
        Date date = toDate(futureDate);
        String str = dateTime(date);
        return str;
    }

    /**
     * 获取某天前/后几天的日期
     * @param now
     * @param days
     * @return
     */
    public static Date getDayBeforeOrAfter(LocalDate now, int days) {
        // 将当前日期加上n天
        LocalDate futureTime = now.plusDays(days);
        Date date = toDate(futureTime);
        return date;
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date beginDate, Date endDate) {
        return Math.abs((int) ((endDate.getTime() - beginDate.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 Date ==> LocalDateTime
     */
    public static LocalDateTime toLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    /**
     * 增加 Date ==> LocalDate
     */
    public static LocalDate toLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZonedDateTime  zonedDateTime = instant.atZone(ZoneId.systemDefault());
        return zonedDateTime.toLocalDate();
    }

    /**
     * 获取时间 多少秒后的时间
     *
     * @param now
     * @param second
     * @return
     */
    public static Date getAfterSecondsTime(LocalDateTime now, int second) {
        // 将当前时间加上n秒
        LocalDateTime futureTime = now.plusSeconds(second);
        Date date = toDate(futureTime);
        return date;
    }

    /**
     * 获取时间 多少分钟后的时间
     *
     * @param now
     * @param minute
     * @return
     */
    public static Date getAfterMinuteTime(LocalDateTime now, int minute) {
        // 将当前时间加上n分钟
        LocalDateTime futureTime = now.plusMinutes(minute);
        Date date = toDate(futureTime);
        return date;
    }


    /**
     * 获取时间 多少个小时后的时间
     *
     * @param now
     * @param hours
     * @return
     */
    public static Date getAfterHoursTime(LocalDateTime now, int hours) {
        // 将当前时间加上n小时
        LocalDateTime futureTime = now.plusHours(hours);
        Date date = toDate(futureTime);
        return date;
    }

    /**
     * 获取时间 多少天后的时间
     *
     * @param now
     * @param days
     * @return
     */
    public static Date getAfterDayTime(LocalDateTime now, int days) {
        LocalDateTime futureTime = now.plusDays(days);
        return toDate(futureTime);
    }

    /**
     * 计算两个时间相差多少毫秒
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static Long diffInMilliseconds(Date startTime, Date endTime) {
        return endTime.getTime() - startTime.getTime();
    }

    /**
     * 获取当前月第一天
     *
     * @return
     */
    public static Date getFirstDayOfMonth() {
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
        return toDate(firstDay);
    }

    /**
     * 获取当前月最后一天
     *
     * @return
     */
    public static Date getLastDayOfMonth() {
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
        return toDate(lastDay);
    }


    /**
     * 获取当年的第一天
     *
     * @param
     * @return
     */
    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     *
     * @param
     * @return
     */
    public static Date getCurrYearLast() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
//        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currYearFirst);
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        return calendar.getTime();
    }

    /**
     * 获取当天结束还剩余多少秒
     * @return
     */
    public static int getSeconds(){
        //获取今天当前时间
        Calendar curDate = Calendar.getInstance();
        //获取明天凌晨0点的日期
        Calendar tommorowDate = new GregorianCalendar(
                curDate.get(Calendar.YEAR),
                curDate.get(Calendar.MONTH),
                curDate.get(Calendar.DATE) + 1,
                0, 0, 0);
        //返回 明天凌晨0点 和 今天当前时间 的差值（秒数）
        return (int)(tommorowDate.getTimeInMillis() - curDate .getTimeInMillis()) / 1000;
    }

}
